package com.megvii.koala.presenter;

import com.megvii.corelib.util.SharedPreferenceTool;
import com.megvii.koala.activity.ChangeServerActivity;
import com.megvii.koala.base.KoalaPresenter;
import com.megvii.koala.constance.NetConstance;
import com.megvii.koala.data.model.LoginModel;

/**
 * Created by linyue on 16/2/29.
 */
public class ChangeServerPresenter extends KoalaPresenter<ChangeServerActivity>
        implements ChangeServerActivity.ChangeServerListener
{
    private String tempOfflineAddress = null;

    @Override
    protected void onCreated()
    {
        super.onCreated();
        viewHolder.setListener(this);
        viewHolder.setOnlineAddress(NetConstance.DEFAULT_SERVER_URL);
        String chosenAddress = SharedPreferenceTool
                .getStringValueByKey(viewHolder, LoginModel.KEY_SERVER,
                        NetConstance.DEFAULT_SERVER_URL);
        tempOfflineAddress = SharedPreferenceTool
                .getStringValueByKey(viewHolder, LoginModel.KEY_OFFLINE_SERVER, "");
        if (NetConstance.DEFAULT_SERVER_URL.equals(chosenAddress))
        {
            viewHolder.setStateOnline(true);
            viewHolder.setOfflineAddress(tempOfflineAddress);
        }
        else
        {
            viewHolder.setStateOnline(false);
            viewHolder.setOfflineAddress(chosenAddress);
        }
    }

    @Override
    public void onClickReturn()
    {
        viewHolder.finish();
    }

    @Override
    public void onClickSave()
    {
        boolean choseOnline = viewHolder.isStateOnline();
        String offlineAddress = viewHolder.getOfflineAddress();
        String address = null;
        if (choseOnline)
        {
            address = viewHolder.getOnlineAddress();
        }
        else
        {
            address = offlineAddress;
        }
        SharedPreferenceTool.saveStringValue(viewHolder, LoginModel.KEY_SERVER, address);
        SharedPreferenceTool
                .saveStringValue(viewHolder, LoginModel.KEY_OFFLINE_SERVER, offlineAddress);
        viewHolder.finish();
    }

    @Override
    public void onClickOnline()
    {
        viewHolder.setStateOnline(true);
        viewHolder.setOfflineAddress(tempOfflineAddress);
    }

    @Override
    public void onClickOffline()
    {
        viewHolder.setStateOnline(false);
    }
}
